<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>设备故障维护时长监察图</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          @click="downloadChart">
          下载图表
        </el-button>
      </div>
      <div id="main" style="width: 100%; height: 600px"></div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from "echarts";
import axios from "axios";
import { getToken } from "@/utils/auth";
/* import { WAREHOUSES_PATH } from "../../../api/constants/constants.js"; */

export default {
  name: "ControlChart",
  data() {
    return {
      chartData: null,
      chart: null
    };
  },
  mounted() {
    this.fetchChartData();
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    fetchChartData() {
      const token = getToken();
      // const excelFilePath = encodeURIComponent(WAREHOUSES_PATH);
      axios
        .get(`${process.env.VUE_APP_BASE_API}/wareHouses/control`, {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        })
        .then((response) => {
          console.log("Response data:", response.data);
          try {
            if (typeof response.data === "string") {
              this.chartData = JSON.parse(response.data);
            } else {
              this.chartData = response.data;
            }
            this.initChart();
          } catch (e) {
            console.error("Error parsing JSON:", e);
            this.$message.error("解析图表数据失败");
          }
        })
        .catch((error) => {
          console.error("Error fetching chart data:", error);
          this.$message.error("获取图表数据失败");
        });
    },
    initChart() {
      const chartDom = document.getElementById("main");
      this.chart = echarts.init(chartDom);
      const option = this.chartData;
      this.chart.setOption(option);
    },
    downloadChart() {
      if (!this.chart) {
        this.$message.warning('暂无图表数据');
        return;
      }
      
      const now = new Date();
      const fileName = `设备故障维护时长监察图_${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}.png`;
      
      const imgData = this.chart.getDataURL({
        type: 'png',
        pixelRatio: 2,
        backgroundColor: '#fff'
      });
      
      const link = document.createElement('a');
      link.href = imgData;
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  },
};
</script>

<style scoped>
.box-card {
  margin: 20px;
}
</style>
